<template>
  <div class="user-container">
    <el-card class="box-card">
      <div slot="header"
           class="clearfix">
        <span>更换头像</span>
      </div>
      <div class="text item">
        <el-form ref="userInfo"
                 :model="userInfo">
          <el-form-item prop="avatar">
            <input type="file"
                   multiple
                   id="ava"
                   @change="add"
                   style="display:none" />
            <br>
            <img ref="study"
                 :src="studyDataPic">
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="submitForm('userInfo')">选择头像</el-button>
            <el-button @click="resetForm('userInfo')">上传图片</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUserinfo, setAvatar } from '@/api/user'
export default {
  name: 'UserPage',
  data () {
    return {
      userInfo: {
        avatar: ''
      },
      studyDataPic: require('@/assets/images/avatar.jpg')
    }
  },
  created () {
    this.getUserinfo()
  },
  methods: {
    async getUserinfo () {
      const res = await getUserinfo()
      console.log(res)
      this.userInfo.avatar = res.data.data.user_pic
    },
    async add (e) {
      const file = e.target.files[0]
      if (file.type !== 'image/jpeg' && file.type !== 'image/bmp' && file.type !== 'image/png') {
        this.$message.error('请上传JPEG、JPG、BMP、PNG格式文件')
        e.target.value = ''
        return
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = e => {
        this.studyDataPic = e.target.result
        // this.avatar = file
        // console.log('e.target', e.target)
      }
    },
    submitForm () {
      document.getElementById('ava').click()
    },
    resetForm () {
      this.$refs.userInfo.validate(async isOK => {
        // console.log('上传数据：', this.studyDataPic)
        // console.log('上传数据格式：', typeof this.studyDataPic)
        this.userInfo.avatar = this.studyDataPic
        await setAvatar(this.userInfo)
        // console.log('返回信息', res)
        this.$message.success('更新数据成功')
        this.getUserinfo()
      })
    }
  }
}
</script>

<style>
</style>
